package com.cup.bddm.handler;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.cup.bddm.api.controller.BaseController;
import com.cup.bddm.api.service.UserLogService;
import com.cup.bddm.impala.po.User;
import com.cup.bddm.util.JsonUtil;
import com.cup.bddm.util.WebUtil;

/**
 * 所有Controller拦截器
 */
@Aspect
@Component
public class ControllerHandler extends BaseController {
	@Autowired
	public HttpServletRequest req;

	@Autowired
	public UserLogService userLogService;

	@Before(value = "execution(* com.cup.bddm.*.controller.*.*(..)))")
	public void before(JoinPoint joinPoint) {
		StringBuilder sb = new StringBuilder();
		String contentType = req.getContentType() + "-" + WebUtil.getUserAgent(req);
		if (contentType.contains("application/json")) {
			try {
				Object[] args = joinPoint.getArgs();
				if (args.length > 0) {
					for (Object obj : args) {
						sb.append(JsonUtil.toJson(obj));
					}
				} else {
					sb.append("empty");
				}
			} catch (Exception e) {
				sb.append("unknown");
			}
		} else {
			sb.append(JsonUtil.toJson(req.getParameterMap()));
		}
		req.setAttribute(GlobalHandler.REQ_BODY, sb.toString());
	}

	@AfterReturning(value = "execution(* com.cup.bddm.*.controller.*.*(..)))", returning = "retValue")
	public void after(JoinPoint joinPoint, Object retValue) {
		StringBuilder sb = new StringBuilder();
		if (retValue == null) {
			sb.append(" null");
		} else if (retValue.getClass().getName().endsWith("Vo")) {
			sb.append(JsonUtil.toJson(retValue));
		} else {
			sb.append(retValue.toString());
		}
		String res_body = sb.toString();
		req.setAttribute(GlobalHandler.RES_BODY, res_body);
		// 用户登录改密日志
		String req_path = req.getRequestURI();
		if (req_path.contains("/api/user/login") || req_path.contains("/services/user/login") || req_path.contains("/services/user/pwd")) {
			String path = req_path.split("user/")[1];
			String[] arr = path.split("/");
			User user = user();
			String cup_branch_ins_id_cd = user.getCup_branch_ins_id_cd();
			String login_name = user.getLogin_name();
			String req_ip = WebUtil.getIpAddr(req);
			long req_time = (long) req.getAttribute(GlobalHandler.REQ_TIME);
			String req_type = arr[0];
			String res_stat = res_body.startsWith("{\"state\":\"00\"") ? "成功" : "失败";
			String req_src = WebUtil.getUserAgent(req);
			userLogService.asyncSave(cup_branch_ins_id_cd, login_name, req_ip, req_time, req_type, res_stat, req_src);
		}
	}

}
